# Contributor: Leo <thinkabit.ukim@gmail.com>
# Maintainer: Natanael Copa <ncopa@alpinelinux.org>
_luaversions="5.1 5.2 5.3 5.4"
pkgname=lua-rex
pkgver=2.9.2
pkgrel=0
pkgdesc="Lua bindings to regular expression library pcre2 and posix"
options="!check" # TODO: get testsuite
url="http://lrexlib.luaforge.net/"
arch="all"
license="MIT"
depends="lua-rex-pcre2 lua-rex-posix"
makedepends="pcre2-dev"
subpackages="$pkgname-pcre2:_pcre2 $pkgname-posix:_posix"

for _i in $_luaversions; do
	makedepends="$makedepends lua$_i-dev lua$_i"
	subpackages="$subpackages lua$_i-rex-pcre2:_split
		lua$_i-rex-posix:_split"
done

source="$pkgname-$pkgver.tar.gz::https://github.com/rrthomas/lrexlib/archive/rel-${pkgver//./-}.tar.gz"

builddir="$srcdir"/lrexlib-rel-${pkgver//./-}

prepare() {
	default_prepare

	local _ver
	for _ver in $_luaversions; do
		cp -r "$builddir" "$srcdir"/build-$_ver
	done
}

_build_variant() {
	local _ver=$1
	local _obj=$2
	local _flags="$3"

	${CC:-gcc} \
		$CFLAGS \
		$(pkg-config --cflags lua$_ver) \
		-shared \
		-fPIC \
		-o $_obj.${pkgver%.*} \
		$_flags \
		-DVERSION=\"$pkgver\" \
		-DLUA_COMPAT_5_2
	ln -s $_obj.${pkgver%.*} $_obj
}

build() {
	local _ver
	for _ver in $_luaversions; do
		msg "build for Lua $_ver"
		cd "$srcdir"/build-$_ver
		_build_variant $_ver rex_pcre2.so \
			'src/common.c src/pcre2/lpcre2.c src/pcre2/lpcre2_f.c
			-lpcre2-8 -DPCRE2_CODE_UNIT_WIDTH=8'

		_build_variant $_ver rex_posix.so \
			'src/common.c src/posix/lposix.c'

	done
}

package() {
	mkdir -p "$pkgdir"
}

_pcre2() {
	pkgdesc="Lua bindings to pcre2 regular expressions library"
	depends=
	mkdir -p "$subpkgdir"
}

_posix() {
	pkgdesc="Lua bindings to posix regular expressions library"
	depends=
	mkdir -p "$subpkgdir"
}

_split() {
	local _ver=${subpkgname%%-*}
	_ver=${_ver#lua}
	local _lib=${subpkgname##*-}
	pkgdesc="Lua $_ver bindings to $_lib regular expressions library"
	install_if="lua$_ver lua-rex-$_lib=$pkgver-r$pkgrel"
	depends=
	install -d "$subpkgdir"/usr/lib/lua/$_ver

	cp -a "$srcdir"/build-$_ver/rex_$_lib.so* \
		"$subpkgdir"/usr/lib/lua/$_ver

}

sha512sums="
e7fa4ab3ea00ef54748712194e8b19473b51fd8cc8cfe56b5521a16c7bab05dcd191aae5408b50de846bb9939fbf09e4e9aaccd53424c1ce8c22947078e30cd3  lua-rex-2.9.2.tar.gz
"
